﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace DX3906;

public class Game1 : Game
{
    private GraphicsDeviceManager _graphics;
    private SpriteBatch _spriteBatch;
    
    private Texture2D texture;
    private Vector2 position;
    private float speed = 100f; // 图片移动速度
    private int earthWH = 200; // 地球显示大小

    public Game1()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        // 设置窗口大小为1024x768
        _graphics.PreferredBackBufferWidth = 1024;
        _graphics.PreferredBackBufferHeight = 768;
        _graphics.ApplyChanges();
        
        // 加载图片
        texture = Content.Load<Texture2D>("pixalearth50");
        // 初始化图片位置
        position = new Vector2(-earthWH, (_graphics.PreferredBackBufferHeight - earthWH) / 2);
        
        // 订阅窗口大小变化事件
        Window.ClientSizeChanged += Window_ClientSizeChanged;

        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
            Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here
        // 获取每帧的时间间隔
        float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
        // 更新图片位置
        position.X += speed * deltaTime;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        _spriteBatch.Begin();
        // 绘制图片，并将其大小设置为200x200像素
        _spriteBatch.Draw(texture, new Rectangle((int)position.X, (int)position.Y, earthWH, earthWH), Color.White);
        _spriteBatch.End();

        base.Draw(gameTime);
    }
    
    private void Window_ClientSizeChanged(object sender, EventArgs e)
    {
        // 获取当前窗口大小
        int width = Window.ClientBounds.Width;
        int height = Window.ClientBounds.Height;

        // 根据窗口大小调整图片位置
        position.X = -texture.Width; // 初始位置在窗口左边外面
        position.Y = (height - texture.Height) / 2; // 垂直居中
    }
}